<!--
 @description 柱状图公共组件（基于zengqiongying老师的柱状图组件做修改，满足同一页面使用多个柱状图动态传送图表数据渲染视图）
 @fileName Histogram.vue
 @author maliang
 @created 2021/09/26 14:05:00
-->
<template>
  <div>
    <div :id="chartId" ref="myEchart" class="echart_container" />
  </div>
</template>

<script>
import { v4 as uuidv4 } from 'uuid'
export default {
  name: 'Histogram',
  props: {
    xAxisData: {
      type: Array,
      default: () => {
        return null
      }
    }, // x轴数据:示例["累积未发车数", "当日累积未发", "两日以上未发"]
    seriesData: {
      type: Array,
      default: () => {
        return [] // 示例: [{name: "洋马配送中心",data: [120, 100, 440],},{name: "清丰配送中心",data: [200, 120, 240]},{ name: "潜江配送中心",data: [34, 57, 234],}]
      }
    },
    seriesBarConfig: {
      type: Object,
      default: () => {}
    },
    showLegend: {
      type: Boolean,
      default: true
    }
  },
  data() {
    const _this = this
    return {
      windowSize: [0, 0],
      chartId: `echart-bar-${uuidv4()}`, // 用UUID生成图表id，防止id重复
      chart: { map: null, chartData: [] },
      chartColors: [
        '#16BC83',
        '#FEB81D',
        '#FF8A8A',
        '#4FD8D3',
        '#73A0FA',
        '#5FBCFF',
        '#909399',
        '#906299',
        '#905311',
        '#908006'
      ], // 绿色，黄色，蓝色
      echartOption: {
        title: {
          text: '',
          show: false
        },
        color: _this.chartColors,
        tooltip: {
          trigger: 'axis',
          textStyle: {
            color: '#333333',
            fontFamily: 'PFZH',
            fontSize: 12,
            lineHeight: 26
          },
          extraCssText: 'z-index: 9', // 设置层级
          axisPointer: {
            type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        legend: {
          data: [],
          show: _this.showLegend,
          align: 'left',
          left: 0,
          top: 0,
          itemWidth: 12, // 图例图标的宽
          itemHeight: 12, // 图例图标的高
          padding: [0, 0, 5, 5],
          icon: 'square', // 图例的形状
          lineStyle: {
            opacity: 0
          },
          textStyle: {
            color: '#888888',
            fontFamily: 'PFZH'
          }
        },
        grid: {
          left: '5',
          right: '10',
          bottom: '0',
          top: '40',
          containLabel: true,
          show: false
        },
        toolbox: {
          show: false,
          feature: {
            saveAsImage: {}
          }
        },
        xAxis: {
          type: 'category',
          data: [],
          axisLine: {
            show: false
          },
          axisTick: {
            show: false // x轴刻度隐藏
          },
          axisLabel: {
            // 坐标轴字体颜色
            color: '#CCCCCC'
          }
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            // 坐标轴字体颜色
            color: '#CCCCCC'
          }
        },
        series: []
      },
      initChartFinish: false // 图表初始化是否完成
    }
  },
  computed: {
    // 是否开始绘制地图（监听数据获取完成、图表初始化完成后绘制地图）
    isStartDrawChart() {
      if (this.xAxisData && this.initChartFinish) {
        return true
      }
      return false
    }
  },
  watch: {
    windowSize() {
      this.chart.map.resize()
    },
    isStartDrawChart: {
      handler(val) {
        if (val) {
          this.drawChart()
        } else {
          this.chart.map.clear()
          this.showLoading()
        }
      }
    }
  },
  created() {
    const _this = this
    const xAxis = this.echartOption.xAxis
    xAxis.axisLabel.rotate = 40 // X轴字体倾斜40度
    xAxis.axisLabel.fontSize = 10 // 字体大小
    this.$set(this.echartOption, 'xAxis', xAxis)

    this.echartOption.tooltip.formatter = (params) => {
      let tipMsg = `${params[0].name}<br>`
      for (const i in params) {
        const item = params[i]
        tipMsg += `${item.seriesName}：<span style="color:${
          item.color
        }">${_this.foramtThousand(
          Number(item.data).toFixed(2)
        )}</span> <br>`
      }
      return `<div class="echart-tooltip-content">${tipMsg}</div>`
    }
    if (this.chartColors && this.chartColors.length) {
      this.$set(this.echartOption, 'color', this.chartColors)
    }
  },
  mounted() {
    this.initChart()
  },
  methods: {
    initChart() {
      this.windowSize = [
        document.body.clientWidth,
        document.body.clientHeight
      ]
      window.addEventListener('resize', () => {
        this.windowSize = [
          document.body.clientWidth,
          document.body.clientHeight
        ]
      })
      this.chart.map = this.$echarts.init(
        document.getElementById(this.chartId)
      )
      this.showLoading()
      this.initChartFinish = true
    },
    showLoading() {
      this.chart.map.showLoading({
        color: '#12B9A3',
        fontFamily: 'PFZH',
        textColor: '#CCCCCC',
        fontSize: 14,
        lineWidth: 2
      }) // loading样式
    },
    hideLoading() {
      this.chart.map.hideLoading() // 隐藏loading样式
    },
    async drawChart() {
      // if (this.chart.map) {
      //     this.chart.map.dispatchAction({
      //         type: "hideTip",
      //     });
      // }
      this.chart.map.clear()
      this.echartOption.xAxis.data = this.xAxisData
      this.echartOption.legend.data = []
      this.echartOption.series = []
      this.seriesData.forEach((item, index) => {
        this.echartOption.legend.data.push(item.name)
        item = Object.assign(
          {
            type: 'bar',
            barGap: '76%',
            barWidth: '12px',
            itemStyle: {
              normal: {
                color: (params) => {
                  const colorlist = this.chartColors
                  if (this.seriesData.length <= 1) {
                    return colorlist[params.dataIndex]
                  } else {
                    return colorlist[index]
                  }
                },
                label: {
                  show: true,
                  position: 'top',
                  textStyle: {
                    fontWeight: 'bolder',
                    fontSize: '12',
                    fontFamily: 'PFZH'
                  }
                }
              }
            }
          },
          item,
          this.seriesBarConfig
        )
        this.echartOption.series.push(item)
      })

      this.hideLoading()
      this.chart.map.setOption(this.echartOption)
      this.$nextTick(() => {
        setTimeout(() => {
          this.chart.map.resize()
        }, 300)
      })
      // 高亮时触发
      this.chart.map.off('highlight')
      this.chart.map.on('highlight', (params) => {
        if (params && params.batch && params.batch.length) {
          const batchItem = params.batch[0]
          const xIndex = batchItem.dataIndex
          this.$emit('selectedCallback', xIndex)
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.echart_container {
    height: 300px;
}
</style>
